package alpaca.view.panels;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSpinner;
import javax.swing.ListSelectionModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;

import net.miginfocom.swing.MigLayout;
import alpaca.core.IUser;
import alpaca.core.UserList;
import alpaca.ctrl.ControllerFactory;
import alpaca.ctrl.SearchLogCtrl;

public class LogPanel extends JPanel {
	private static final String CHECKBOX_SHOW_ALL = "Show all";
	private DefaultListModel listModel;
	private DefaultListModel listModel2;
	private JList list;
	private JList list2;
	private final Action action = new GetLogsAction();
	private final JComboBox combobox;
	private final JSpinner spinner;
	private final JCheckBox checkbox;

	/**
	 * Create the panel.
	 */
	public LogPanel() {
		
		listModel = new DefaultListModel();
		listModel2 = new DefaultListModel();

		setLayout(new MigLayout("", "[grow]", "[379px,grow]"));
		
		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		add(panel, "cell 0 0,grow");
		panel.setLayout(new MigLayout("", "[grow][grow]", "[][][][grow][]"));
		
		JLabel lblSelectTheMessages = new JLabel("Select a user to see the messages he/she has sent or received.");
		panel.add(lblSelectTheMessages, "cell 0 0 2 1");
		
		JLabel lblNewLabel_4 = new JLabel("Select two users to see the messages between them.");
		panel.add(lblNewLabel_4, "cell 0 1 2 1");
		
		JLabel lblNewLabel_1 = new JLabel("From:");
		panel.add(lblNewLabel_1, "cell 0 2");
		
		JLabel lblNewLabel = new JLabel("To:");
		panel.add(lblNewLabel, "cell 1 2");
		
		JScrollPane scrollPane = new JScrollPane();
		panel.add(scrollPane, "cell 0 3,grow");

		list = new JList();
		scrollPane.setViewportView(list);
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		list.setModel(listModel);
		
		list.addMouseListener(new MouseAdapter() {

		    int lastSelectedIndex;

		    @Override
			public void mouseClicked(MouseEvent e) {

		        int index = list.locationToIndex(e.getPoint());

		        if (index != -1 && index == lastSelectedIndex) {
		            list.clearSelection();
		        }

		        lastSelectedIndex = list.getSelectedIndex();
		    }
		});
		
		JScrollPane scrollPane_1 = new JScrollPane();
		panel.add(scrollPane_1, "cell 1 3,grow");
		
		list2 = new JList();
		scrollPane_1.setViewportView(list2);
		list2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		list2.setModel(listModel2);
		
		list2.addMouseListener(new MouseAdapter() {

		    int lastSelectedIndex;

		    @Override
			public void mouseClicked(MouseEvent e) {

		        int index = list2.locationToIndex(e.getPoint());

		        if (index != -1 && index == lastSelectedIndex) {
		        	list2.clearSelection();
		        }

		        lastSelectedIndex = list2.getSelectedIndex();
		    }
		});
		
		JPanel panel_1 = new JPanel();
		panel.add(panel_1, "cell 0 4 2 1,grow");
		
		checkbox = new JCheckBox(CHECKBOX_SHOW_ALL);
		panel_1.add(checkbox);
		
		ItemListener itemListener = new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent evt) {
				if (evt.getStateChange() == ItemEvent.SELECTED){
					combobox.setEnabled(false);
					spinner.setEnabled(false);
				} else if (evt.getStateChange() == ItemEvent.DESELECTED){
					combobox.setEnabled(true);
					spinner.setEnabled(true);
				}
				
			}
	      };
		
	    checkbox.addItemListener(itemListener);
	      
		JSeparator separator = new JSeparator();
		separator.setOrientation(SwingConstants.VERTICAL);
		separator.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		panel_1.add(separator);

		JLabel lblNewLabel_2 = new JLabel("View logs back to");
		panel_1.add(lblNewLabel_2);
		
		spinner = new JSpinner();
		spinner.setModel(new SpinnerNumberModel(1, 1, 50, 1));
		panel_1.add(spinner);
		
		combobox = new JComboBox();
		combobox.setModel(new DefaultComboBoxModel(new String[] {"hours", "days", "weeks", "months", "years"}));
		panel_1.add(combobox);
		
		JLabel lblNewLabel_3 = new JLabel("ago");
		panel_1.add(lblNewLabel_3);
		
		JButton btnNewButton = new JButton("Get Messages");
		panel_1.add(btnNewButton);
		btnNewButton.setAction(action);
	}
	
	public void fillUserList(UserList userList){
        listModel.clear();
        for(IUser user : userList) {
        	listModel.addElement(user);
        } 
        listModel2.clear();
        for(IUser user : userList) {
        	listModel2.addElement(user);
        }   
	}

	private class GetLogsAction extends AbstractAction {
		public GetLogsAction() {
			putValue(NAME, "Get Logs");
			putValue(SHORT_DESCRIPTION, "Get logs for the selected users");
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			
			if (list.getSelectedValue() != null || list2.getSelectedValue() != null){
				Date date;
				if (!(checkbox.getSelectedObjects() == null)){
					date = new Date(0);
				} else {
					String dateType = (String)combobox.getSelectedItem();
					int amount = (Integer) spinner.getValue();
					Calendar calendar = new GregorianCalendar();
					
					if (dateType.equals("hours")){
						calendar.add(Calendar.HOUR_OF_DAY, -amount);
					} else if (dateType.equals("days")){
						calendar.add(Calendar.DATE, -amount);
					} else if (dateType.equals("weeks")){
						calendar.add(Calendar.WEEK_OF_YEAR, -amount);
					} else if (dateType.equals("months")){
						calendar.add(Calendar.MONTH, -amount);
					} else if (dateType.equals("years")){
						calendar.add(Calendar.YEAR, -amount);
					}
					date = new Date(calendar.getTimeInMillis());
				}
	            SearchLogCtrl ctrl = (SearchLogCtrl) ControllerFactory.getController(SearchLogCtrl.class);
	            ctrl.setSearch((IUser)list.getSelectedValue(), (IUser)list2.getSelectedValue(), date);
	            ctrl.execute();
			}

		}
	}
}
